package com.zxh.system.service.impl;

import com.zxh.system.exception.MethodNotDefinedException;
import com.zxh.system.entity.AbstractIdEntity;
import com.zxh.system.repository.BaseRepository;
import com.zxh.system.service.BaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.io.Serializable;
import java.util.Optional;

public abstract class AbstractBaseServiceImpl<T> implements BaseService<T> {

    protected abstract BaseRepository<T,Serializable> getRepository();

    public Optional<T> get(String idFiled,Serializable id) {
        return getRepository().findOne((r,q,cb)->cb.equal(r.get(idFiled),id));
    }

    @Override
    public Optional<T> get(Serializable id) {
        throw new MethodNotDefinedException(getClass(),"get");
    }

    @Override
    public T load(Serializable id) {
        return getRepository().getOne(id);
    }

    @Override
    public void add(T t) {
        getRepository().save(t);
    }

    @Override
    public void update(T t) {
        if(t instanceof AbstractIdEntity){
            AbstractIdEntity e=(AbstractIdEntity) t;
            BeanUtils.copyProperties(e,load(e.getId()));
        }else
            throw new MethodNotDefinedException(getClass(),"update");
    }

    @Override
    public void delete(Serializable id) {
        getRepository().deleteById(id);
    }

    @Override
    public Page<T> query(PageRequest page, T t) {
        return getRepository().findAll(page);
    }
}
